package cc.mrbird.febs.system.controller;


import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.domain.FebsConstant;
import cc.mrbird.febs.common.domain.QueryRequest;
import cc.mrbird.febs.common.utils.ExcelUtils;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.utils.SortUtil;
import cc.mrbird.febs.system.domain.CostList;
import cc.mrbird.febs.system.domain.HospitalData;
import cc.mrbird.febs.system.domain.HospitalizationStatistics;
import cc.mrbird.febs.system.service.GroupService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 福小林
 */
@Slf4j
@Validated
@RestController
@RequestMapping("hospitalization")
public class HospitalizationController extends BaseController {



    @Resource
    private GroupService groupService;


    /**
     * 小组管理列表数据查询
     * @param hospitalizationStatistics 查询条件
     * @return 返回数据
     */
    @RequestMapping("/hospitalList")
    @RequiresPermissions("report:view")
    public List<Map<String, Object>> hospitalList(HospitalizationStatistics hospitalizationStatistics) {
        Map<String, Object> searchData = getSearchData(hospitalizationStatistics);
        //小组相关医生的信息
        List<Map<String, Object>> outpatientStatistics = groupService.getOutpatientStatistics(searchData);
        for (Map<String, Object> temp : outpatientStatistics) {
            Object userId = temp.get("userId");
            searchData.put("orderDoctorId", userId);
            List<Map<String, Object>> outpatientStatisticsList = groupService.getOutpatientStatisticsList(searchData);
            temp.put("costList", outpatientStatisticsList);
        }
        return outpatientStatistics;
    }





    private Map<String, Object> getSearchData(HospitalizationStatistics hospitalizationStatistics) {
        //开始时间
        String startDate = hospitalizationStatistics.getStartDate();
        //结束时间
        String endDate = hospitalizationStatistics.getEndDate();
        //项目集合
        String items = hospitalizationStatistics.getItems();
        //部门ids
        String deptIds = hospitalizationStatistics.getDeptIds();
        //小组ids
        String groupIds = hospitalizationStatistics.getGroupIds();
        String hospitalDeptType = hospitalizationStatistics.getHospitalDeptType();
        String userId = hospitalizationStatistics.getUserId();
        Map<String, Object> map = new HashMap<>(16);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("userId", userId);
        map.put("items", FebsUtil.getIds(items));
        map.put("deptIds", FebsUtil.getIds(deptIds));
        map.put("groupIds", FebsUtil.getIds(groupIds));
        map.put("hospitalDeptType", FebsUtil.getIds(hospitalDeptType));
        return map;
    }

    /**
     * 门诊概况
     * @param hospitalizationStatistics 查询条件
     * @return 返回数据
     */
    @RequestMapping("/hospitalListPage")
    @RequiresPermissions("report:view")
    public Map<String, Object>  hospitalListPage(HospitalizationStatistics hospitalizationStatistics, QueryRequest request) {
        Map<String, Object> searchData = getSearchData(hospitalizationStatistics);
        Page<HospitalData> page = new Page<>();
        SortUtil.handlePageSort(request, page, "userId", FebsConstant.ORDER_ASC, false);
        //小组相关医生的信息
        IPage<HospitalData> outpatientStatistics = groupService.getOutpatientStatisticsPage(page, searchData);
        //医院科室分类  门诊 住院 门特
        String hospitalDeptType = hospitalizationStatistics.getHospitalDeptType();
        List<String> hospitalDeptTypeList=new ArrayList<>();
        List<HospitalData> records = outpatientStatistics.getRecords();
        setTableData(searchData, hospitalDeptType, hospitalDeptTypeList, records);
        return getDataTable(outpatientStatistics);
    }

    private void setTableData(Map<String, Object> searchData, String hospitalDeptType, List<String> hospitalDeptTypeList, List<HospitalData> records) {
        for (HospitalData record : records) {
            String userId = record.getUserId();
            searchData.put("orderDoctorId", userId);
            List<CostList> outpatientStatisticsList1 =new ArrayList<>();
            List<CostList> outpatientStatisticsList2 =new ArrayList<>();
            List<CostList> outpatientStatisticsList3 =new ArrayList<>();
            List<CostList> outpatientStatisticsList4 =new ArrayList<>();
            if(StringUtils.isEmpty(hospitalDeptType)){
                hospitalDeptTypeList.add("门诊");
                hospitalDeptTypeList.add("住院");
                hospitalDeptTypeList.add("门特");
                for (int i =0; i <hospitalDeptTypeList.size() ; i++) {
                    searchData.put("hospitalDeptType", FebsUtil.getIds(hospitalDeptTypeList.get(i)));
                    if (i==0){
                        outpatientStatisticsList1 = getCostLists(searchData);
                    }
                    if (i==1){
                        outpatientStatisticsList2 = getCostLists(searchData);
                    }
                    if (i==2){
                        outpatientStatisticsList3 = getCostLists(searchData);
                    }
                }
                  hospitalDeptTypeList.clear();
                 searchData.remove("hospitalDeptType");
                 outpatientStatisticsList4 = getCostLists(searchData);

            }else {
                searchData.put("hospitalDeptTypes",FebsUtil.getIds(hospitalDeptType));
                String[] split = hospitalDeptType.split(",");
                for (int i = 0; i <split.length ; i++) {
                    searchData.put("hospitalDeptType",FebsUtil.getIds(split[i]));
                    if ("门诊".equals(split[i])){
                         outpatientStatisticsList1 = getCostLists(searchData);
                    }
                    if ("住院".equals(split[i])){
                         outpatientStatisticsList2 = getCostLists(searchData);
                    }
                    if ("门特".equals(split[i])){
                      outpatientStatisticsList3 = getCostLists(searchData);
                    }
                }

                searchData.remove("hospitalDeptType");
                outpatientStatisticsList4 = getCostLists(searchData);

            }


            List<Map<String,Object>>  hello=new ArrayList<>();

            Map<String,Object> a1=new HashMap<>(16);
            Map<String,Object> a2=new HashMap<>(16);
            Map<String,Object> a3=new HashMap<>(16);
            Map<String,Object> a4=new HashMap<>(16);
            if (outpatientStatisticsList1!=null&&!outpatientStatisticsList1.isEmpty()){
                a1.put("typename","门诊");
                a1.put("costList",outpatientStatisticsList1);
                hello.add(a1);

            }
            if (outpatientStatisticsList2!=null&&!outpatientStatisticsList2.isEmpty()) {
                a2.put("typename", "住院");
                a2.put("costList", outpatientStatisticsList2);
                hello.add(a2);
            }
            if (outpatientStatisticsList3!=null&&!outpatientStatisticsList3.isEmpty()) {
                a3.put("typename", "门特");
                a3.put("costList", outpatientStatisticsList3);
                hello.add(a3);
            }
            a4.put("typename","合计");
            a4.put("costList",outpatientStatisticsList4);
            hello.add(a4);
            record.setResultList(hello);
        }
    }

    private List<CostList> getCostLists(Map<String, Object> searchData) {
        List<CostList> outpatientStatisticsList1= groupService.getOutpatientStatisticsListPage(searchData);
        List<CostList> costLists = groupService.getDrugProportion(searchData);
        setHospitalTypeData(costLists.get(0), outpatientStatisticsList1);
        return outpatientStatisticsList1;
    }


    private void setHospitalTypeData(CostList costList,List<CostList> result) {
        CostList temp2=new CostList();
        temp2.setName("药占比");
        temp2.setValue(costList.getDrugProportion());
        result.add(temp2);
        CostList temp3=new CostList();
        temp3.setName("耗材比");
        temp3.setValue(costList.getConsumablesProportion());
        result.add(temp3);
        CostList temp4=new CostList();
        temp4.setName("人数");
        temp4.setValue(costList.getPatientNumber());
        result.add(temp4);
        CostList temp1=new CostList();
        temp1.setName("总费用");
        temp1.setValue(costList.getTotalMoney());
        result.add(temp1);
    }



    /**
     *
     * @param response  浏览器相应
     * @param request  获取前端传入的值 测试暂时未用
     * @return String
     */
    @RequestMapping("/exportExcel")
    @ResponseBody
    public  String exportExcel(HttpServletResponse response, HttpServletRequest request,HospitalizationStatistics hospitalizationStatistics){
        try{
            response.setContentType("application/binary;charset=UTF-8");
            ServletOutputStream out=response.getOutputStream();
            //设置文件头：最后一个参数是设置下载文件名(这里我们叫：张三.pdf)
            String excelName="数据导出";
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(excelName+".xls", "UTF-8"));
            //用作传入的参数不正确时，返回给浏览器的提示信息
            if (StringUtils.isEmpty(excelName)){
                response.getWriter().print("传入参数不全!");
                return "传入参数不全";
            }
            Map<String, Object> searchData = getSearchData(hospitalizationStatistics);
            //小组相关医生的信息
            List<HospitalData> outpatientStatistics = groupService.getOutpatientStatisticsPageExcel( searchData);

            //医院科室分类  门诊 住院 门特
            String hospitalDeptType = hospitalizationStatistics.getHospitalDeptType();
            List<String> hospitalDeptTypeList=new ArrayList<>();
            setTableData(searchData, hospitalDeptType, hospitalDeptTypeList, outpatientStatistics);

            //拼装测试数据
            LinkedMap<String,String> titleMap=new LinkedMap<>();
            titleMap.put("groupName","小组名称");
            titleMap.put("groupMemberName","成员名称");
            titleMap.put("deptName","所属科室");
            titleMap.put("typename","类别");
            ExcelUtils.exportExcel(titleMap, out,outpatientStatistics);
            return "success";
        } catch(Exception e){
            return "导出信息失败";
        }
    }



    /**
     * 小组管理列表数据查询
     * @return 返回数据
     */
    @RequestMapping("/getGroupListById")
    @ResponseBody
    public List<Map<String, Object>> getGroupListById(String deptIds) {
        //小组相关医生的信息
        List<Map<String, Object>> groupList = groupService.getGroupListById(FebsUtil.getIds(deptIds));
        return groupList;
    }



}
